#include <QtGui>

#include "includes/usercollection.h"

// default constructor
UserCollection::UserCollection() : QList<User>() {
	
}

// save as xml file
bool UserCollection::save(const QString& filename) {
	// open file
	QFile file(filename);
	file.open(QIODevice::WriteOnly);
	// open stream to file
	QTextStream outputStream(&file);
	// create xml doc
	QDomDocument doc("users");

	// create root node
	QDomElement root = doc.createElement("users");
	doc.appendChild(root);

	// add nodes
        foreach (User u, *this) {
		// create node
		QDomElement element = doc.createElement("user");
		// configure to represent user
                u.toDomElement(element);
		root.appendChild(element);
	}
	doc.save(outputStream, 0); // 0 ??
	file.close();

	return true; // return value? 
}

// load from xml file.
// NOTE: User pointers must be deleted!
bool UserCollection::load(const QString& filename) {
	// open file as text stream
	QFile file(filename);
	file.open(QIODevice::ReadOnly);
	QTextStream inputStream(&file);
	
	// create dom document
	QDomDocument doc("users");
	// load
	doc.setContent(&file);
	file.close();

	// load all 'user' nodes
	QDomNodeList userNodes = doc.elementsByTagName("user");
	for (int i = 0; i < userNodes.size(); i++) {
		// create new user object on heap
		User* newUser = new User();
		QDomElement elem = userNodes.item(i).toElement();
		newUser->fromDomElement(elem);
		// add it
                append(*newUser);
                delete newUser;
	}

	return true; // return value?
}
